package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.WalletAvatarAndNameSetupActivity;
import com.pansoft.openplanet.activity.WalletTypeSelectActivity;
import com.pansoft.openplanet.adapter.ChildWalletListAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.widget.StarAssetWalletPopup;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.bitcoincashj.core.Coin;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Bch钱包列表fragment
 * @author will
 */
public class BchWalletListFragment extends BaseFragment implements View.OnClickListener {

    public static final String TAG = "BchWalletListFragment";
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ChildWalletListAdapter childWalletListAdapter;
    private ArrayList<AssetListBean> assetList = new ArrayList<>();//当前关注的代币列表
    private int mode = IPAssetsConstant.CHAIN_ID_BCH;
    private String balance = "0";//钱包余额


    private LinearLayout llEmptyLayout;
    private Button tvCreateWallet;
    private Button tvRestoreWallet;
    private ImageView ivIcon;
    private TextView tvTextTitle;
    private ProgressBar progressBar;
    private Account currentAccout;


    public BchWalletListFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_wallet_list, container, false);
        initView(rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (currentAccout != null) {
            String filePath = currentAccout.getFileName();
//            BtcTransactionManager.getInstance(currentAccout.getAddress(), filePath)
//                    .removeOnSyncListener(this);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletChanged(Account account) {
        // refreshLayout.isEnableRefresh();
        balance = "0";
        if (!account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)) {
            //只有btc 需要同步
            return;
        }
        if (currentAccout.getAddress().equals(account.getAddress())) {
            return;
        }
        currentAccout = account;
        // startSyncBtcData(account);
    }

    /**
     * 同步后更新余额
     *
     * @param balance1
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBalanceUpdated(Coin balance1) {
        if (assetList.size() > 0)
            assetList.get(0).setBalance(balance1.toFriendlyString());
        childWalletListAdapter.setData(balance1.toFriendlyString());
        balance = balance1.toFriendlyString();
    }

    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        childWalletListAdapter = new ChildWalletListAdapter(getContext(), assetList, mode);
        recyclerView.setAdapter(childWalletListAdapter);

        llEmptyLayout = (LinearLayout) rootView.findViewById(R.id.ll_empty_layout);
        tvCreateWallet = (Button) rootView.findViewById(R.id.tv_create_wallet);
        tvRestoreWallet = (Button) rootView.findViewById(R.id.tv_restore_wallet);
        refreshLayout = (SmartRefreshLayout) rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setVisibility(View.VISIBLE);
        llEmptyLayout.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvTextTitle = (TextView) rootView.findViewById(R.id.tv_text_title);
        tvRestoreWallet.setOnClickListener(this);
        tvCreateWallet.setOnClickListener(this);
        progressBar = rootView.findViewById(R.id.progressbar);
        initSwipeRefreshView(rootView);
    }

    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefreshView(View rootView) {
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void initData() {
//        if (mode == MODE_BTC) {
        recyclerView.setVisibility(View.VISIBLE);
        refreshLayout.setVisibility(View.VISIBLE);
        llEmptyLayout.setVisibility(View.GONE);
        ivIcon.setImageDrawable(getResources().getDrawable(R.drawable.ipasset_wallet_list_bch));
        tvTextTitle.setText("BCH");
        assetList.clear();
        AccountDao accountDao = new AccountDao(getActivity());

        Account account = accountDao.getCurrentShowAccount(IPAssetsConstant.ChainEnum.BCH);
        if (account == null) {
            List<Account> accounts = accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.BCH);
            if (accounts.size() == 0) {
                refreshLayout.setVisibility(View.GONE);
                llEmptyLayout.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
                ivIcon.setImageDrawable(getResources().getDrawable(R.drawable.ipasset_wallet_list_bch));
                tvTextTitle.setText("BCH");
                return;
            } else {
                account = accounts.get(0);
                account.setCurrentShow(true);
                accountDao.insertOrReplace(account);
                refreshLayout.setVisibility(View.VISIBLE);
                llEmptyLayout.setVisibility(View.GONE);
            }
        }

        currentAccout = account;
        //请求余额 eventbus 返回数据

        // FIXME: 18-9-4
//        UTXOTransactionManager.getBalance(account.getAddress());

        assetList.add(new AssetListBean.Builder().type(1)
                .address(account.getAddress())
                .name(account.getAcccountName())
                .icon(account.getAccountAvatar())
                .isSelected(true)
                .balance(balance)
                .build());
        assetList.add(new AssetListBean.Builder().type(0)
                .address(account.getAddress())
                .name(account.getAcccountName())
                .icon(account.getAccountAvatar())
                .isSelected(true)
                .balance(balance)
                .build());

        childWalletListAdapter.setData(assetList.get(0).getBalance());
        childWalletListAdapter.notifyDataSetChanged();

        refreshLayout.finishRefresh();

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_create_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_CREATE_NEW,
                    IPAssetsConstant.CHAIN_ID_BCH);
        } else if (id == R.id.tv_restore_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_RESTORE_OLD,
                    IPAssetsConstant.CHAIN_ID_BCH);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
        if (id.equals("bch")) {
            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), IPAssetsConstant.CHAIN_ID_BCH);
        }

    }
}
